package main.model.json;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Type;

import com.google.gson.stream.JsonReader;

/** json files handling class
 * 
 * @author Tomek Wagner
 * 
 */
public class JsonFile
{
	/**
	 * Saving object to a file
	 * @param path - path to file
	 * @param object - object to save 
	 * @return - boolean if saved correctly
	 */
	public static <T> boolean save(String path, T object)
	{
		try 
		{
			saveJsonStream(path, object);
			return true;
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			return false;
		}				
	}
	
	/**
	 Loading object from file
	 * @param path - path to file
	 * @param classType - type of object to load (e.g. String.class)
	 * @return object of specific type
	 */
	public static <T> T load(String path, Type classType)
	{
		try
		{
			boolean exists = (new File(path)).exists();
			if (!exists)
			{
			   return null;
			}
			return readJsonStream(new FileInputStream(path), classType);
		}
		catch (FileNotFoundException e) 
		{			
			e.printStackTrace();
		}
		catch (IOException e) 
		{			
			e.printStackTrace();
		}
		return null;
	}
	
	/*
	 * read from inputstream with specific type
	 */
	 private static <T> T readJsonStream(InputStream in, Type classType) throws IOException 
	 {
		 InputStreamReader i = new InputStreamReader(in, "UTF-8");
		 if(i.ready()) // not empty
		 {
		     JsonReader reader = new JsonReader(i);
		     T obj;
		     try 
		     {
		    	 obj = JsonSerializer.deserialize(reader, classType);		    	 
		     } 
		     finally
		     {
		         reader.close();
		         i.close();
		     }
		     return obj;
		 }
		 return null;
	 } 

	 /*
	  * save object to file
	  */
	 private static <T> void saveJsonStream(String filePath, T object) throws IOException 
	 {					 
		 Writer out = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");			     //$NON-NLS-1$
		 out.write(JsonSerializer.serialize(object));			 
		 out.close();
	 }
	
}
